package com.ccteam.fluidmusic.ui.local.artist

import android.app.Application
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import androidx.lifecycle.*
import com.ccteam.fluidmusic.ui.PARENT_ID_KEY
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.fluidmusic.common.MusicServiceConnectionFlow
import com.ccteam.fluidmusic.fluidmusic.media.extensions.METADATA_KEY_ALBUM_ID
import com.ccteam.fluidmusic.fluidmusic.media.extensions.METADATA_KEY_ARTIST_ID
import com.ccteam.model.Resource
import com.ccteam.shared.result.BaseItemData.Companion.LAYOUT_ALBUM_LIST_ITEM_SMALL
import com.ccteam.shared.result.album.AlbumListItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/2/9
 *
 * 本地歌手详情页专辑内容ViewModel
 **/
@HiltViewModel
class LocalArtistDetailAlbumViewModel @Inject constructor(
    private val musicServiceConnectionFlow: MusicServiceConnectionFlow,
    application: Application,
    savedStateHandle: SavedStateHandle
): AndroidViewModel(application) {

    private val _albumItems = MutableLiveData<Resource<List<AlbumListItem>>>(Resource.Loading(null))
    val albumItems: LiveData<Resource<List<AlbumListItem>>> = _albumItems
    private var parentId: String? = null

    /**
     * 订阅回调
     * 收到具体专辑内容的信息后进入协程进行处理
     */
    private val subscriptionCallback = object : MediaBrowserCompat.SubscriptionCallback() {
        override fun onChildrenLoaded(parentId: String, children: List<MediaBrowserCompat.MediaItem>) {
            viewModelScope.launch {
                handleArtistAlbumItem(children)
            }
        }
    }

    init {
        savedStateHandle.get<String>(PARENT_ID_KEY)?.let {
            this.parentId = it
            musicServiceConnectionFlow.subscribe(it, subscriptionCallback)
        }
    }

    /**
     * 未知年份字符
     */
    private val unknownYear: String = application.getString(R.string.description_unknown_year)

    private suspend fun handleArtistAlbumItem(children: List<MediaBrowserCompat.MediaItem>){
        withContext(Dispatchers.Default){
            val application = getApplication<Application>()
            val itemsList = children.map { child ->
                // 获得年份，如果为0则是未知年份
                val year = if(child.description.extras?.getLong(MediaMetadataCompat.METADATA_KEY_YEAR) != 0L){
                    child.description.extras?.getLong(MediaMetadataCompat.METADATA_KEY_YEAR).toString()
                } else {
                    unknownYear
                }
                // 拼凑subtitle，显示 年份 + 专辑歌曲数
                val subtitle = application.getString(R.string.description_artist_list_item_type_1,year,child.description.extras?.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS))
                AlbumListItem(
                    child.mediaId!!,
                    child.description.title.toString(),
                    child.description.iconUri.toString(),
                    child.description.subtitle.toString(),
                    subtitle,
                    child.description.extras?.getString(METADATA_KEY_ALBUM_ID) ?: "-1",
                    child.description.extras?.getString(METADATA_KEY_ARTIST_ID) ?: "-1",
                    year,
                    LAYOUT_ALBUM_LIST_ITEM_SMALL
                )
            }
            _albumItems.postValue(Resource.Success(itemsList))
        }
    }

    override fun onCleared() {
        super.onCleared()
        parentId?.let {
            musicServiceConnectionFlow.unsubscribe(it,subscriptionCallback)
        }
    }
}